
import java.io.*;
import java.net.*;

import javax.imageio.ImageIO;
import javax.swing.JOptionPane;

//import org.apache.commons.httpclient.*;
//import org.apache.commons.httpclient.methods.PostMethod;

public class UploadImage extends Thread{
	EditedImage imageArray;
	ImageUploader parent;

	String done = "-1";
	float part = 0.f;
	float ukPart = 1.0f;
	SyncFlag flag;
	
	String uploadUrl; 
	
	String urlPath; 
	
	UploadImage (EditedImage imageArray, ImageUploader parent, String url) {		
		
		uploadUrl = url;
		
		this.imageArray = imageArray;
		this.parent = parent;

		
		urlPath = this.uploadUrl;
	}
	
	
	float progres = 0.0f;
	float max;
    String boundary = "nrnrnrnrnrnrnnrnrnrnnrnrnnrnrnnrn";
    String dashes = "--";
    String newLine = "\r\n";    
    
	public HttpURLConnection getUrlConnection() {  
		  try {

		    URL                url; 
		    HttpURLConnection  urlConn;     
		    
		    
		    url = new URL(urlPath); 
		    urlConn = (HttpURLConnection)url.openConnection();
		    urlConn.setRequestMethod("POST");
		    urlConn.setDoInput(true); 
		    urlConn.setDoOutput(true); 
		    urlConn.setUseCaches(false); 
		    //urlConn.setRequestProperty ("Content-Type", "multipart/form-data" );
		    urlConn.setRequestProperty ("Content-Type", "multipart/form-data; boundary=" + boundary);
		    //urlConn.setRequestProperty ("Content-Transfer-Encoding","binary");
		    
		    		    		    
		    return urlConn;
		  	}
		  
		catch (MalformedURLException mue) { 
		     JOptionPane.showMessageDialog(null, mue.getMessage());
			 }		
		catch (IOException ioe) { 
			JOptionPane.showMessageDialog(null, ioe.getMessage());
			}
		
		return null;
		}
	
	public DataOutputStream getOutputStream(HttpURLConnection urlConn) {
		DataOutputStream dos = null;
		try {
			dos = new DataOutputStream (urlConn.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return dos;		
		}
		    
	public void uploadFile(EditedImage image, DataOutputStream dos) throws IOException {		
		    dos.writeBytes(dashes);
	        dos.writeBytes(boundary);
	        dos.writeBytes(newLine);	        	        
	        
		    ByteArrayOutputStream baos = new ByteArrayOutputStream();
		    
	        try {
	            ImageIO.write(image.getResizedImage(), image.type, baos);
	        } catch (IOException ex) {
	            JOptionPane.showMessageDialog(null, "Neispravna datoteka!");
	            this.done = "0";	            
	            return;
	        }	        	        
	        	        
	        
	        byte[] array = baos.toByteArray();
	        max = array.length;
	        
	        dos.writeBytes("Content-Disposition: form-data; name=\"" + 0+ "\"; filename=\"" + URLEncoder.encode(parent.getParameter("dir"), "UTF-8") + "\"");
	        dos.writeBytes(newLine);
	        dos.writeBytes("Content-Type: " + image.type);
	        //dos.writeBytes(newLine);
	        dos.writeBytes("Content-Transfer-Encoding: binary");
	        dos.writeBytes(newLine);
	        dos.writeBytes(newLine);
	        //JOptionPane.showMessageDialog(parentComponent, message)
	        for (int i = 0; i < array.length; i++) {
	        	
	        	dos.write(array[i]);
	        	if (i%1000 == 0) {	
	        		
	        		//this.setProgress((int)((i/max)*part*100));
	        		this.progres = (i/max) * 1/ukPart + part/ukPart;
	        		//this.firePropertyChange("progress", -1f, (Object)this.progres);	        			
	        		//parent.progres.setProgress(this.progres);
	        		flag.get("upload");
	        		}
	        	}
	        dos.writeBytes(newLine);
	        dos.flush();
	        dos.writeBytes(dashes);
	        dos.writeBytes(boundary);
	        dos.writeBytes(dashes);	    
	        dos.writeBytes(newLine);
	        
		    dos.flush(); 		    

			  
		  return;

		} 
	
	public void closeConnection(DataOutputStream dos) {
		try {
			dos.close();
		} 
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			}			
	    }

	public String getResponse(HttpURLConnection urlConn) {	    
	    BufferedReader     dis;					    
	    
	    String s = "fail";
		try {
			dis = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
			s = dis.readLine();
			dis.close(); 
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    
	    return s;
	    	    	  
		}
	
	
	public void uploadImages() {
		HttpURLConnection conn = this.getUrlConnection();
		DataOutputStream dos = this.getOutputStream(conn);
		
		
		try {
			this.uploadFile(imageArray, dos);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		this.closeConnection(dos);
		
		String response = this.getResponse(conn);
		
		if (response.equals("fail")) { 
	    	this.done =  "0";
	    	this.flag.release();
	    	return;
	    } 
		else { 
	    	this.done =  response;		
	    	this.flag.release();
	    	return;
	    }
	}

	
	public void run() {
		this.uploadImages();
				
		}
}